<template>
  <a-drawer
    title="选择优惠券"
    :visible="visible"
    :destroyOnClose="true"
    :width="1000"
    :body-style="{
      paddingBottom: '80px',
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflow: 'auto',
    }"
    :maskClosable="true"
    @close="closeModal"
  >
    <a-table
      :columns="couponColumns"
      :data-source="tableList"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      :rowSelection="rowSelection"
      :scroll="{ x: 'max-content' }"
      rowKey="id"
    >
    </a-table>

    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button type="primary" @click.prevent="onSubmit">确定</a-button>
    </div>
  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import { Form, message, notification } from "ant-design-vue";
import request from "@/common/utils/request";
import store from "@/store";
import _ from "lodash";

export default defineComponent({
  name: "SelectCouponList",
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
    rows: {
      type: Array,
      default: () => {
        return [];
      },
    },
    grantType: {
      type: Number,
      default: 1, // 1 为单个发放 2 为批量发放
    },
    // 批量时租客数量
    ownerNum: {
      type: Number,
      default: 0,
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      couponColumns: COUPON_COLUMNS,
      tableList: [],
      loading: false,
      selectRows: [],
      selectedRowKeys: [],
    });

    // todo... 金额为0 的账单 可以用 computed 实现

    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    /* 选择 */
    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
      getCheckboxProps: getCheckboxProps,
    }));

    // 禁用逻辑
    const isDisabled = (record) => {
      return record.num
        ? props.grantType === 2
          ? record.num - (record?.received_num || 0) < props.ownerNum
          : record.num - (record?.received_num || 0) < 1
        : false;
    };

    const getCheckboxProps = (record) => {
      return {
        disabled: isDisabled(record),
      };
    };

    const onSelect = (record, selected, selectedRows, nativeEvent) => {
      if (selected) {
        let rows = [...state.selectRows, record];
        state.selectRows = rows.filter((item, index, self) => {
          // 利用findIndex方法找到第一个与当前元素id相等的元素索引
          const i = self.findIndex((t) => t.id === item.id);
          // 如果当前索引等于当前元素在self中的最初出现位置索引，则表示元素符合要求，不是重复元素，保留
          return i === index;
        });
        state.selectedRowKeys = Array.from(
          new Set([...state.selectedRowKeys, record.id])
        );
      } else {
        state.selectRows = state.selectRows.filter((v) => v.id !== record.id);
        state.selectedRowKeys = state.selectedRowKeys.filter(
          (v) => v !== record.id
        );
      }
    };

    const onSelectAll = (selected, selectedRows, changeRows) => {
      if (selected) {
        let rows = [...state.selectRows, ...selectedRows.filter((o) => o)];
        state.selectRows = rows.filter((item, index, self) => {
          // 利用findIndex方法找到第一个与当前元素id相等的元素索引
          const i = self.findIndex((t) => t.id === item.id);
          // 如果当前索引等于当前元素在self中的最初出现位置索引，则表示元素符合要求，不是重复元素，保留
          return i === index;
        });
        state.selectedRowKeys = Array.from(
          new Set([
            ...state.selectedRowKeys,
            ...selectedRows.filter((o) => o).map((o) => o.id),
          ])
        );
      } else {
        state.selectRows = state.selectRows.filter(
          (o) => !changeRows.find((row) => row.id === o.id)
        );
        state.selectedRowKeys = state.selectedRowKeys.filter(
          (o) => !changeRows.find((row) => row.id === o)
        );
      }
    };

    // 提交
    const onSubmit = () => {
      if (state.selectedRowKeys.length) {
        emit("submitSelect", state.selectRows);
      } else {
        message.warn("请选择优惠券");
      }
    };

    // 触发关闭
    const closeModal = () => {
      emit("closeModal");
    };

    const getTableList = () => {
      let params = {};
      params.page = page.value;
      params.limit = limit.value;
      state.loading = true;
      request
        .post("/org", "/coupon/list", params)
        .then((res) => {
          total.value = res?.total || 0;
          state.tableList = res?.list || [];
          state.loading = false;
        })
        .catch((err) => {
          state.loading = false;
        });
    };

    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
      getTableList();
    };

    const init = () => {
      getTableList();
      if (props.rows.length) {
        state.selectedRowKeys = props.rows.map((v) => v.id);
        state.selectRows = _.cloneDeep(props.rows);
      }
    };

    const resetData = () => {
      page.value = 1;
      limit.value = 10;
      total.value = 0;
      state.tableList = [];
      state.loading = false;
      state.selectRows = [];
      state.selectedRowKeys = [];
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          // 打开时初始化数据
          init();
        } else {
          // 关闭时重置数据
          resetData();
        }
      }
    );
    return {
      ...toRefs(state),
      pagination,
      rowSelection,
      closeModal,
      onSubmit,
      handleTableChange,
    };
  },
});

const COUPON_COLUMNS = [
  {
    title: "优惠券名称",
    key: "name",
    dataIndex: "name",
    width: 200,
    fixed: "left",
    align: "center",
  },
  {
    title: "绑定项目",
    dataIndex: "village_name",
    key: "village_name",
    width: 240,
    align: "center",
  },
  {
    title: "优惠券金额",
    dataIndex: "amount",
    key: "amount",
    width: 150,
    customRender: ({ text, record, index }) => {
      return record.attribute == 1
        ? `￥${record.amount}`
        : record.attribute == 2
        ? `${record.amount}折`
        : "--";
    },
    align: "center",
  },
  {
    title: "优惠条件",
    dataIndex: "condition",
    key: "condition",
    width: 200,
    customRender: ({ text, record, index }) => {
      return record?.use_premise?.condition === "billPrice"
        ? `满￥${record?.use_premise?.num || 0}可用`
        : record?.use_premise?.condition === "billMonth"
        ? `缴纳账单满足${record?.use_premise?.num || 0}个月可用`
        : record?.use_premise?.condition === "billCount"
        ? `满${record?.use_premise?.num || 0}个账单可用`
        : "--";
    },
    align: "center",
  },
  {
    title: "可用的费用类型",
    dataIndex: "cost_names",
    key: "cost_names",
    width: 240,
    align: "center",
    customRender: ({ text, record, index }) => {
      return text?.length ? text.join("、") : "";
    },
  },
  {
    title: "优惠券数量",
    dataIndex: "num",
    key: "num",
    width: 150,
    customRender: ({ text, record, index }) => {
      return text || "无限制";
    },
    align: "center",
  },
  {
    title: "每用户领取上限",
    dataIndex: "got_num",
    key: "got_num",
    width: 150,
    customRender: ({ text, record, index }) => {
      return text || "无限制";
    },
    align: "center",
  },
  {
    title: "剩余优惠券数量",
    dataIndex: "received_num",
    key: "received_num",
    width: 150,
    customRender: ({ text, record, index }) => {
      return record.num ? record.num - (record?.received_num || 0) : "";
    },
    align: "center",
  },
];
</script>

<style lang="less" scoped></style>
